using System.Collections;
using UnityEngine;

public class RotateItem : MonoBehaviour
{
    [Header("Cube Generation Settings")] [SerializeField]
    private int Count = 5; // 生成立方体的数量

    [SerializeField] private float CircleRadius = 3f; // 圆形布局的半径
    [SerializeField] private Vector3 CenterPosition = Vector3.zero; // 圆形中心点位置
    [SerializeField] private Vector3 TargetPosition; // 旋转目标位置

    [Header("Rotation Settings")] [SerializeField]
    private float RotationSpeed = 90f; // 每秒旋转角度

    [SerializeField] private Transform CameraTransform;

    [Header("Card Effect Settings")] [SerializeField]
    private float ScaleMultiplier = 1.5f; // 放大倍数

    [SerializeField] private float ScaleDuration = 5f; // 放大持续时间
    [SerializeField] private float ScaleTransitionSpeed = 2f; // 缩放过渡速度
    [SerializeField] private float CameraDistance = 2f; // 移动到摄像机前方的距离
    [SerializeField] private float MoveTransitionSpeed = 2f; // 移动过渡速度

    private bool isRotating = false;
    private Transform[] Items;
    private Color[] ItemColors;
    private Vector3[] OriginalScales;
    private Vector3[] OriginalPositions;
    private int SelectedIndex = -1;
    private Coroutine ScaleCoroutine;
    private Coroutine MoveCoroutine;

    // 预定义的颜色数组
    private Color[] AvailableColors =
    {
        Color.red,
        Color.blue,
        Color.green,
        Color.yellow,
        Color.magenta,
        Color.cyan,
        new Color(1f, 0.5f, 0f), // 橙色
        new Color(0.5f, 0f, 1f), // 紫色
        new Color(1f, 0.75f, 0.8f), // 粉色
        new Color(0.5f, 1f, 0.5f) // 浅绿色 
    };

    void Start()
    {
        // 获取摄像机引用
        if (CameraTransform == null)
        {
            CameraTransform = Camera.main.transform;
        }

        GenerateItems();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && !isRotating)
        {
            StartCoroutine(RotateItems());
        }
    }

    void GenerateItems()
    {
        Items = new Transform[Count];
        ItemColors = new Color[Count];
        OriginalScales = new Vector3[Count];
        OriginalPositions = new Vector3[Count];

        TargetPosition = CenterPosition;
        TargetPosition.z -= CircleRadius;

        for (int i = 0; i < Count; i++)
        {
            // 计算圆形布局位置
            float angle = (360f / Count) * i * Mathf.Deg2Rad;
            Vector3 position = CenterPosition + new Vector3(
                CircleRadius * Mathf.Cos(angle),
                0,
                CircleRadius * Mathf.Sin(angle)
            );

            // 创建立方体
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.name = $"Cube_{i}";
            cube.transform.SetParent(transform);
            cube.transform.localPosition = position;

            Color cubeColor = AvailableColors[i % AvailableColors.Length];
            ItemColors[i] = cubeColor;

            Renderer renderer = cube.GetComponent<Renderer>();
            Material material = new Material(Shader.Find("Standard"));
            material.color = cubeColor;
            renderer.material = material;

            Items[i] = cube.transform;
            // 相对于父对象的缩放比例
            OriginalScales[i] = cube.transform.localScale;
            // 相对于父对象的本地坐标位置
            OriginalPositions[i] = cube.transform.localPosition;
        }
    }


    IEnumerator RotateItems()
    {
        isRotating = true;

        // 随机选择一个立方体
        int newSelectedIndex = Random.Range(0, Count);

        // 如果之前有选中的立方体，先恢复其大小
        if (SelectedIndex >= 0)
        {
            if (ScaleCoroutine != null)
            {
                StopCoroutine(ScaleCoroutine);
            }

            // 只恢复缩放，不恢复位置（因为我们不再移动单个立方体）
            StartCoroutine(ScaleItem(SelectedIndex, OriginalScales[SelectedIndex], ScaleTransitionSpeed));
        }

        SelectedIndex = newSelectedIndex;

        float targetRotationAngle = CalculateRotationAngleToCamera(SelectedIndex);

        float rotationAmount = 0f;

        // 执行旋转动画，直到选中的立方体到达摄像机前方
        while (rotationAmount < targetRotationAngle)
        {
            float rotationStep = RotationSpeed * Time.deltaTime;

            // 确保不会超过目标角度
            if (rotationAmount + rotationStep > targetRotationAngle)
            {
                rotationStep = targetRotationAngle - rotationAmount;
            }

            rotationAmount += rotationStep;

            // 围绕父对象中心点旋转
            transform.Rotate(0, rotationStep, 0);

            yield return null;
        }

        // 旋转完全结束后处理选中的立方体
        if (SelectedIndex >= 0)
        {
            Transform selectedCube = Items[SelectedIndex];
            Vector3 directionToCamera = CameraTransform.position - selectedCube.position;
            directionToCamera.y = 0;

            if (directionToCamera != Vector3.zero)
            {
                selectedCube.rotation = Quaternion.LookRotation(directionToCamera);
            }

            // 只进行放大效果，不移动立方体
            Vector3 targetScale = OriginalScales[SelectedIndex] * ScaleMultiplier;
            ScaleCoroutine = StartCoroutine(ScaleAndResetItem(SelectedIndex, targetScale));
        }

        isRotating = false;
    }

    // 计算旋转角度
    float CalculateRotationAngleToCamera(int cubeIndex)
    {
        Vector3 OA = Items[cubeIndex].position - CenterPosition;
        Vector3 OB = TargetPosition - CenterPosition;

        // Mathf.Atan2(OA.z, OA.x)是与x轴之间的夹角
        float angleA = Mathf.Atan2(OA.z, OA.x) * Mathf.Rad2Deg;
        float angleB = Mathf.Atan2(OB.z, OB.x) * Mathf.Rad2Deg;

        // 把差值限制在 [0, 360)
        if (angleA < 0) angleA += 360f;
        if (angleB < 0) angleB += 360f;

        float delta = angleB - angleA;

        if (delta > 0)
        {
            delta = 360 - delta;
        }
        else
        {
            delta = Mathf.Abs(delta);
        }

        if (delta < 180)
        {
            delta += 360;
        }
        return delta;
    }

    IEnumerator ScaleAndResetItem(int cubeIndex, Vector3 targetScale)
    {
        // 放大
        yield return StartCoroutine(ScaleItem(cubeIndex, targetScale, ScaleTransitionSpeed));

        // 等待指定时间
        yield return new WaitForSeconds(ScaleDuration);

        // 只恢复原始大小，不恢复位置
        StartCoroutine(ScaleItem(cubeIndex, OriginalScales[cubeIndex], ScaleTransitionSpeed));

        // 重置选中状态
        if (SelectedIndex == cubeIndex)
        {
            SelectedIndex = -1;
        }
    }

    IEnumerator ScaleItem(int cubeIndex, Vector3 targetScale, float speed)
    {
        Transform cube = Items[cubeIndex];
        Vector3 startScale = cube.localScale;
        float elapsedTime = 0f;
        float duration = 1f / speed;

        while (elapsedTime < duration)
        {
            elapsedTime += Time.deltaTime;
            float t = elapsedTime / duration;

            // 使用平滑插值
            cube.localScale = Vector3.Lerp(startScale, targetScale, Mathf.SmoothStep(0f, 1f, t));

            yield return null;
        }

        cube.localScale = targetScale;
    }

    // 在编辑器中实时预览圆形布局
    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position + CenterPosition, CircleRadius);

        // 绘制立方体位置预览
        for (int i = 0; i < Count; i++)
        {
            float angle = (360f / Count) * i * Mathf.Deg2Rad;
            Vector3 position = transform.position + CenterPosition + new Vector3(
                CircleRadius * Mathf.Cos(angle),
                0,
                CircleRadius * Mathf.Sin(angle)
            );

            // 根据是否被选中使用不同颜色
            Gizmos.color = (i == SelectedIndex) ? Color.green : Color.red;
            Gizmos.DrawWireCube(position, Vector3.one);
        }
    }
}